import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/config/constant.dart';
import 'package:kkhousekeep/net/home_repair_connect.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/shared_preferences.dart';
import 'package:kkhousekeep/tools/string_ext.dart';
import 'package:kkhousekeep/tools/toast_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../../../models/home_room_entity.dart';
import '../../../../models/repair_fault_type_entity.dart';
import '../../../../net/respnse_code.dart';
import '../../../public/take_picture_screen.dart';

class RepairAddController extends GetxController {
  var address = ''.obs;

  var addressOfOut = "";

  var repairAreaType = RepairAreaType.indoors.obs;

  UrgencyType? urgencyType;

  var faultTypeIndex = -1;

  var faultTypeList = <RepairFaultTypeObj>[].obs;

  final ImageDescModel placeholderModel = ImageDescModel(
      isPlaceholder: true,
      absolutePath: 'home_convenient_repair_add_image.png');

  var imageDescList = <ImageDescModel>[].obs;

  var isReadyOK = false.obs;

  late HomeRepairConnect _connect;

  late TextEditingController faultDescController;

  late TextEditingController nameController;

  late TextEditingController phoneController;

  @override
  void onInit() {
    _connect = Get.find();
    faultDescController = TextEditingController();
    nameController = TextEditingController();
    phoneController = TextEditingController();
    _loadNetworkData();
    imageDescList.add(placeholderModel);
    _loadSPInformation();
    super.onInit();
  }

  void performClickSubmit() async {
    if (isReadyOK.value) {
      List<String> pics = [];
      if (!phoneController.text.checkCNPhone()) {
        ToastUtils.showToast(tip: "请输入正确的手机号码");
        return;
      }
      for (var element in imageDescList) {
        if (!element.isPlaceholder && element.networkPath.isNotEmpty) {
          pics.add(element.networkPath);
        }
      }
      DialogUtil.showNetworkLoading();
      var response = await _connect.submitOrder(
        area: repairAreaType.value.id,
        address: repairAreaType.value.id == 1 ? address.value : addressOfOut,
        committer: nameController.text,
        phone: phoneController.text,
        urgency: urgencyType?.id ?? -1,
        faultTypeId: faultTypeList[faultTypeIndex].id,
        mark: faultDescController.text,
        pics: pics,
      );
      DialogUtil.dismiss();
      if (response == null) {
        return;
      }
      if (response.code == ResponseCode.success) {
        Get.back(result: Constant.resultOK);
        return;
      }
      DialogUtil.showNetworkFail();
    }
  }

  void performClickImageItem(ImageDescModel model) {
    if (model.isPlaceholder) {
      ///点击占位图
      FocusManager.instance.primaryFocus?.unfocus();
      Get.to(() => TakePictureScreen(
            photoPathCallBack: <PickPictureModel>(model) {
              if (imageDescList.length > 2) {
                imageDescList.remove(placeholderModel);
              }
              imageDescList.add(ImageDescModel(
                networkPath: model.netPath,
                absolutePath: model.cachePath,
              ));
            },
          ));
      return;
    }

    ///展示图片
    FocusManager.instance.primaryFocus?.unfocus();
    Get.to(() => DisplayPictureScreen(
          imagePath: model.absolutePath,
          isShowRetake: false,
        ));
  }

  void performClickDeleteImage(ImageDescModel model) {
    imageDescList.remove(model);
    bool hasPlaceholder = imageDescList.any((element) => element.isPlaceholder);
    if (!hasPlaceholder) {
      imageDescList.insert(0, placeholderModel);
    }
  }

  void onChange({
    int? repairAreaIndex,
    int? urgencyIndex,
    int? faultTypeIndex,
    String? address,
    String? name,
    String? phone,
    String? faultDesc,
  }) {
    if (repairAreaIndex != null &&
        repairAreaIndex > -1 &&
        repairAreaIndex < RepairAreaType.values.length) {
      repairAreaType.value = RepairAreaType.values[repairAreaIndex];
    }

    if (urgencyIndex != null &&
        urgencyIndex > -1 &&
        urgencyIndex < UrgencyType.values.length) {
      urgencyType = UrgencyType.values[urgencyIndex];
    }

    this.faultTypeIndex = faultTypeIndex ?? this.faultTypeIndex;
    addressOfOut = address ?? addressOfOut;
    checkIsReady();
  }

  void checkIsReady() {
    isReadyOK.value = checkSubmitParameter();
  }

  bool checkSubmitParameter() {
    if (repairAreaType.value.id == 1 && address.value.isEmpty) {
      return false;
    }
    if (repairAreaType.value.id == 2 && addressOfOut.isEmpty) {
      return false;
    }
    if (nameController.text.isEmpty ||
        phoneController.text.isEmpty ||
        faultDescController.text.isEmpty) {
      return false;
    }

    if (urgencyType == null || faultTypeIndex == -1) {
      return false;
    }

    return true;
  }

  void _loadNetworkData() async {
    faultTypeList.value = await _connect.getPropertyFaultType();
  }

  Future<void> _loadSPInformation() async {
    var sp = await SharedPreferences.getInstance();
    HomeRoomObjList roomObjList = HomeRoomObjList.fromJson(
        jsonDecode(sp.getString(SpKey.roomInfo) ?? ''));
    address.value = "${roomObjList.unitName}${roomObjList.roomName}";
    nameController.text = await getSp().getOwnerName();
    phoneController.text = await getSp().getPhone();
  }
}

class ImageDescModel {
  bool isPlaceholder;
  String networkPath;
  String absolutePath;

  ImageDescModel({
    this.isPlaceholder = false,
    this.networkPath = '',
    this.absolutePath = "",
  });
}

enum RepairAreaType {
  indoors(id: 1, name: '户内'),
  outside(id: 2, name: '公区');

  final int id;
  final String name;

  const RepairAreaType({
    required this.id,
    required this.name,
  });

  static String getNameById(int id) {
    return RepairAreaType.values
            .firstWhereOrNull((element) => element.id == id)
            ?.name ??
        '';
  }
}

enum UrgencyType {
  ordinary(id: 1, name: '一般'),
  urgent(id: 2, name: '紧急'),
  veryUrgent(id: 3, name: '非常紧急');

  final int id;
  final String name;

  const UrgencyType({
    required this.id,
    required this.name,
  });

  static String getNameById(int id) {
    return UrgencyType.values
            .firstWhereOrNull((element) => element.id == id)
            ?.name ??
        '';
  }
}
